from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware

from app.core.middlewares.exception_handler_middleware import ExceptionHandlerMiddleware
from app.core.middlewares.login_log_middleware import LoginLogMiddleware
from app.core.middlewares.operation_log_middleware import OperationLogMiddleware


def handle_middleware(app: FastAPI):
    """
    中间件是按照"先进后出"（FILO）的顺序执行的
    """
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=9)
    app.add_middleware(LoginLogMiddleware)
    app.add_middleware(OperationLogMiddleware)
    # app.add_middleware(HTTPSRedirectMiddleware)
    # app.add_middleware(AuthenticationMiddleware)
    # 异常处理(ExceptionHandlerMiddleware)会最先看到请求，最后看到响应
    app.add_middleware(ExceptionHandlerMiddleware)
